package cn.yr.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.yr.common.core.domain.dto.SysUserDto;
import cn.yr.common.core.domain.entity.SysUser;
import cn.yr.common.core.domain.vo.PageVo;
import cn.yr.system.mapper.SysUserMapper;
import cn.yr.system.service.ISysUserService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhyd.oauth.model.AuthUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
* @title SysUserServiceImpl
* @description
* @author Lang 1102076808@qq.com
* @date 2021/3/21 17:09
*/
@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

	@Resource
	private SysUserMapper sysUserMapper;

	@Override
	public PageVo<SysUser> pageUser(PageVo<SysUser> pageVo, Wrapper<SysUser> wrapper) {
		return sysUserMapper.pageUser(pageVo,wrapper);
	}

	@Override
	public void addAuthUser(AuthUser authUser) {
		SysUser sysUser = new SysUser();
		BeanUtil.copyProperties(authUser,sysUser,true);

		sysUser.setOauthType(authUser.getSource());
		if(ObjectUtil.isNotEmpty(authUser.getGender())){
			sysUser.setSex(authUser.getGender().getCode());
		}
		if(StrUtil.isEmpty(sysUser.getUserName())){
			sysUser.setUserName("nfyr"+ RandomUtil.randomString(6));
		}
		if(StrUtil.isEmpty(sysUser.getNickName())){
			sysUser.setNickName(sysUser.getUserName());
		}
		sysUser.setUserType("1");
		sysUser.setCreateTime(new Date());
		sysUserMapper.insert(sysUser);
	}

	@Override
	public SysUserDto coverSysUser(AuthUser authUser) {
		SysUser sysUser = sysUserMapper.selectByUuid(authUser.getUuid());
		if(ObjectUtil.isEmpty(sysUser)) {
			addAuthUser(authUser);
			sysUser = sysUserMapper.selectByUuid(authUser.getUuid());
		}
		return new SysUserDto(sysUser);
	}
}